package org.emet.service.storage;

import java.util.List;

import org.apache.log4j.Logger;
import org.emet.dao.storage.ItemDao;
import org.emet.entity.storage.Item;
import org.emet.jee.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.security.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 物品管理
 * 
 * @author alex
 * 
 */
@Service
@Transactional
@RemotingDestination
public class ItemManager {
	private Logger logger = Logger.getLogger(ItemManager.class);

	@Autowired
	private ItemDao itemDao;

	public ItemManager() {
	}

	@Secured("A_MODIFY_ITEM")
	public void saveItem(Item item) {
		if (isNew(item)) {
			checkIfExists(item);
		}
		try {
			Item mergedItem = (Item) itemDao.getSession().merge(item);
			itemDao.save(mergedItem);
		} catch (Exception e) {
			final String message = "保存物品时发生错误!";
			logger.error(message, e);
			throw new BusinessException(message);
		}
	}

	private void checkIfExists(Item item) {
		final long existCount = itemDao.findUnique("select count(*) from Item where name=?", item.getName());
		if (existCount > 0)
			throw new BusinessException("已经存在相同名称的项目");
	}

	private boolean isNew(Item item) {
		return item.getId() == null;
	}

	@Secured("A_MODIFY_ITEM")
	public void deleteItem(long id) {
		if (existReferenceItem(id))
			throw new BusinessException("已经在其它地方存在对该物品的引用！不能进行删除操作！");
		
		try {
			itemDao.delete(id);
		} catch (Exception e) {
			final String message = "删除物品时发生错误!";
			logger.error(message, e);
			throw new BusinessException(message);
		}
	}

	private boolean existReferenceItem(long id) {
		final long existsPurchaseCount = itemDao.findUnique("select count(*) from PurchaseItem p where p.item.id=?", id);
		final long existsSellCount = itemDao.findUnique("select count(*) from SaleItem s where s.item.id=? ", id);
		return existsPurchaseCount > 0 || existsSellCount > 0 ? true : false;
	}

	@Secured("A_VIEW_ITEM")
	@Transactional(readOnly = true)
	public List<Item> getAll() {
		try {
			return itemDao.getAll();
		} catch (Exception e) {
			final String message = "获取物品时发生错误!";
			logger.error(message, e);
			throw new BusinessException(message);
		}
	}

	@Secured("A_VIEW_ITEM")
	@Transactional(readOnly = true)
	public Item getByCode(String code) {
		try {
			return itemDao.findUniqueBy("code", code);
		} catch (Exception e) {
			final String message = "获取物品时发生错误!";
			logger.error(message, e);
			throw new BusinessException(message);
		}
	}

}
